import request from 'umi-request';

export default {
  namespace: 'employees',

  state: [],

  reducers: {
    updateAll(_, { payload }) {
      const { employees } = payload;
      return employees;
    },

    add(state, { payload }) {
      const { employee: newEmployee } = payload;
      newEmployee.key =
        'E' + String(Math.floor(Math.random() * 1000000)).padStart(6, '0');
      newEmployee.tags = [];
      return state.concat([newEmployee]);
    },

    modify(state, { payload }) {
      const { employee: newEmployee } = payload;
      return state.map((e) => (e.key === newEmployee.key ? newEmployee : e));
    },

    remove(state, { payload }) {
      const { key: targetKey } = payload;
      return state.filter((e) => e.key !== targetKey);
    },
  },

  effects: {
    *getAll(_, { call, put }) {
      const response = yield call(request.get, '/api/data');

      yield put({
        type: 'updateAll',
        payload: {
          employees: response,
        },
      });
    },
    *setAll({ payload }, { call }) {
      console.log('setAll', payload);
      yield call(request.post, '/api/data', { data: payload });
    },
    *create({ payload }, { select, put }) {
      yield put({
        type: 'add',
        payload: payload,
      });
      const state = yield select(({ employees }) => employees);
      console.log('select state', state);
      yield put({
        type: 'setAll',
        payload: state,
      });
    },
    *update({ payload }, { select, put }) {
      yield put({
        type: 'modify',
        payload: payload,
      });
      const state = yield select(({ employees }) => employees);
      console.log('select state', state);
      yield put({
        type: 'setAll',
        payload: state,
      });
    },
    *delete({ payload }, { select, put }) {
      yield put({
        type: 'remove',
        payload: payload,
      });
      const state = yield select(({ employees }) => employees);
      console.log('select state', state);
      yield put({
        type: 'setAll',
        payload: state,
      });
    },
  },
};
